import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:multi_shop/models/merchant.dart';
import 'package:multi_shop/services/merchant.dart';
import 'package:multi_shop/services/product_api.dart';
import '../models/product.dart';
import '../widgets/goods.dart'; // ProductCard

class MerchantHome extends StatefulWidget {
  const MerchantHome({super.key});

  @override
  State<MerchantHome> createState() => _MerchantHomeState();
}

class _MerchantHomeState extends State<MerchantHome> {
  // 获取商家id
  final int merchantId = Get.arguments;
  final _api = MerchantApi();
  ProductApi productApi = ProductApi();
  MallMerchant? merchant;
  List<Product> products = [];
  @override
  void initState() {
    super.initState();
    _initData();
  }

  Future<void> _initData() async {
    final merchantInfo = await _api.getMerchantInfo(merchantId);
    setState(() {
      merchant = merchantInfo;
    });
    getProducts(merchantId);
  }

  // 加载商品列表
  Future<void> getProducts(int merchantId) async {
    final data = await productApi.list(merchantId: merchantId);

    setState(() {
      products = data;
      debugPrint('products: $products');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(merchant?.name ?? '商家')),

      body: merchant == null
          ? const Center(child: CircularProgressIndicator()) // 数据没来前显示loading
          : CustomScrollView(
              slivers: [
                // 商家信息卡片
                SliverToBoxAdapter(
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 商家头像
                        CircleAvatar(
                          radius: 28,
                          backgroundImage: NetworkImage(merchant!.logo),
                        ),
                        const SizedBox(width: 12),
                        // 商家名 + 简介
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                merchant!.name * 2,
                                style: const TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 6),
                              Text(
                                merchant!.desc,
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                // 商品列表
                SliverPadding(
                  padding: const EdgeInsets.all(12),
                  sliver: SliverGrid(
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2, // 两列
                          mainAxisSpacing: 10,
                          crossAxisSpacing: 10,
                          childAspectRatio: 0.7,
                        ),
                    delegate: SliverChildBuilderDelegate((context, index) {
                      final item = products[index];
                      final defaultSku = item.skus.firstWhere(
                        (sku) =>
                            sku.id.toString() == item.defaultSkuId.toString(),
                      );
                      return InkWell(
                        onTap: () => Get.toNamed('/detail', arguments: item.id),
                        child: ProductCard(
                          imageUrl: item.imageUrl,
                          name: item.name,
                          price: defaultSku.price.toString(),
                          sales: item.sales,
                        ),
                      );
                    }, childCount: products.length),
                  ),
                ),
              ],
            ),
    );
  }
}
